<template>
	<view class="container">
		<!-- 日历头部 -->
		<view class="calendar-header">
			<view class="month-nav">
				<button class="nav-btn" @click="prevMonth">
					<uni-icons type="arrowleft" size="18" color="#3B82F6" />
				</button>
				<text class="month-title">{{ currentMonthText }}</text>
				<button class="nav-btn" @click="nextMonth">
					<uni-icons type="arrowright" size="18" color="#3B82F6" />
				</button>
			</view>
			<button class="today-btn" @click="goToday">今天</button>
		</view>

		<!-- 星期标题 -->
		<view class="week-header">
			<text 
				v-for="day in weekDays" 
				:key="day" 
				class="week-day"
			>
				{{ day }}
			</text>
		</view>

		<!-- 日历网格 -->
		<view class="calendar-grid">
			<view 
				v-for="date in calendarDates" 
				:key="date.dateString"
				class="date-cell"
				:class="{
					'other-month': date.isOtherMonth,
					'today': date.isToday,
					'selected': date.dateString === selectedDate,
					'has-schedule': date.schedules.length > 0
				}"
				@click="selectDate(date)"
			>
				<text class="date-number">{{ date.day }}</text>
				<view class="schedule-dots" v-if="date.schedules.length > 0">
					<view 
						v-for="(schedule, index) in date.schedules.slice(0, 3)" 
						:key="schedule.id"
						class="schedule-dot"
						:class="`priority-${schedule.priority}`"
					></view>
					<text v-if="date.schedules.length > 3" class="more-count">+{{ date.schedules.length - 3 }}</text>
				</view>
			</view>
		</view>

		<!-- 选中日期的日程列表 -->
		<view class="selected-date-schedules" v-if="selectedDateSchedules.length > 0">
			<view class="section-title">
				<text>{{ formatSelectedDate }} 的日程</text>
			</view>
			<view class="schedule-list">
				<schedule-card 
					v-for="schedule in selectedDateSchedules" 
					:key="schedule.id"
					:schedule="schedule"
					@toggle-completed="handleToggleCompleted"
					@edit="editSchedule"
					@delete="handleDeleteSchedule"
				/>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-else-if="selectedDate">
			<uni-icons type="calendar" size="48" color="#D1D5DB" />
			<text class="empty-text">{{ formatSelectedDate }} 暂无日程</text>
			<button class="add-schedule-btn" @click="createSchedule">
				添加日程
			</button>
		</view>
	</view>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import ScheduleCard from '../../components/ScheduleCard.vue'

export default {
	name: 'CalendarPage',
	components: {
		ScheduleCard
	},
	
	data() {
		return {
			currentDate: new Date(),
			selectedDate: '',
			weekDays: ['日', '一', '二', '三', '四', '五', '六']
		}
	},
	
	computed: {
		...mapGetters('schedule', ['sortedSchedules']),
		
		// 当前月份文本
		currentMonthText() {
			const year = this.currentDate.getFullYear()
			const month = this.currentDate.getMonth() + 1
			return `${year}年${month}月`
		},
		
		// 格式化选中日期
		formatSelectedDate() {
			if (!this.selectedDate) return ''
			const date = new Date(this.selectedDate)
			const month = date.getMonth() + 1
			const day = date.getDate()
			return `${month}月${day}日`
		},
		
		// 日历日期数组
		calendarDates() {
			const year = this.currentDate.getFullYear()
			const month = this.currentDate.getMonth()
			
			// 获取当月第一天和最后一天
			const firstDay = new Date(year, month, 1)
			const lastDay = new Date(year, month + 1, 0)
			
			// 获取第一周的开始日期（可能是上个月）
			const startDate = new Date(firstDay)
			startDate.setDate(startDate.getDate() - firstDay.getDay())
			
			// 生成6周的日期
			const dates = []
			const today = new Date()
			const todayString = this.formatDateString(today)
			
			for (let i = 0; i < 42; i++) {
				const date = new Date(startDate)
				date.setDate(startDate.getDate() + i)
				
				const dateString = this.formatDateString(date)
				const isCurrentMonth = date.getMonth() === month
				const isToday = dateString === todayString
				
				// 获取当天的日程
				const daySchedules = this.getSchedulesForDate(date)
				
				dates.push({
					date,
					day: date.getDate(),
					dateString,
					isOtherMonth: !isCurrentMonth,
					isToday,
					schedules: daySchedules
				})
			}
			
			return dates
		},
		
		// 选中日期的日程
		selectedDateSchedules() {
			if (!this.selectedDate) return []
			const selectedDateObj = new Date(this.selectedDate)
			return this.getSchedulesForDate(selectedDateObj)
		}
	},
	
	onLoad() {
		this.loadSchedules()
		// 默认选中今天
		this.selectedDate = this.formatDateString(new Date())
	},
	
	onShow() {
		// 更新自定义tabBar选中状态
		if (typeof this.getTabBar === 'function' && this.getTabBar()) {
			this.getTabBar().selected = 1
		}
	},
	
	methods: {
		...mapActions('schedule', ['loadSchedules', 'toggleCompleted', 'deleteSchedule']),
		
		// 格式化日期字符串
		formatDateString(date) {
			const year = date.getFullYear()
			const month = (date.getMonth() + 1).toString().padStart(2, '0')
			const day = date.getDate().toString().padStart(2, '0')
			return `${year}-${month}-${day}`
		},
		
		// 获取指定日期的日程
		getSchedulesForDate(date) {
			const dateString = this.formatDateString(date)
			return this.sortedSchedules.filter(schedule => {
				const scheduleDate = new Date(schedule.endTime)
				const scheduleDateString = this.formatDateString(scheduleDate)
				return scheduleDateString === dateString
			})
		},
		
		// 上一个月
		prevMonth() {
			const newDate = new Date(this.currentDate)
			newDate.setMonth(newDate.getMonth() - 1)
			this.currentDate = newDate
		},
		
		// 下一个月
		nextMonth() {
			const newDate = new Date(this.currentDate)
			newDate.setMonth(newDate.getMonth() + 1)
			this.currentDate = newDate
		},
		
		// 回到今天
		goToday() {
			this.currentDate = new Date()
			this.selectedDate = this.formatDateString(new Date())
		},
		
		// 选择日期
		selectDate(dateInfo) {
			this.selectedDate = dateInfo.dateString
			
			// 如果选择的是其他月份的日期，切换到对应月份
			if (dateInfo.isOtherMonth) {
				this.currentDate = new Date(dateInfo.date)
			}
		},
		
		// 处理完成状态切换
		async handleToggleCompleted(scheduleId) {
			try {
				await this.toggleCompleted(scheduleId)
				uni.showToast({
					title: '状态已更新',
					icon: 'success',
					duration: 1500
				})
			} catch (error) {
				uni.showToast({
					title: '操作失败',
					icon: 'error'
				})
			}
		},
		
		// 编辑日程
		editSchedule(schedule) {
			uni.navigateTo({
				url: `/pages/create/create?id=${schedule.id}&mode=edit`
			})
		},
		
		// 处理删除日程
		async handleDeleteSchedule(scheduleId) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个日程吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							await this.deleteSchedule(scheduleId)
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							})
						} catch (error) {
							uni.showToast({
								title: '删除失败',
								icon: 'error'
							})
						}
					}
				}
			})
		},
		
		// 创建新日程
		createSchedule() {
			// 传递选中的日期作为默认时间
			const selectedDateObj = new Date(this.selectedDate)
			const defaultTime = selectedDateObj.toISOString()
			
			uni.navigateTo({
				url: `/pages/create/create?mode=create&defaultDate=${defaultTime}`
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: $background-gray;
}

.calendar-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: $spacing-lg;
	background-color: $card-white;
	border-bottom: 1px solid $border-gray;
}

.month-nav {
	display: flex;
	align-items: center;
	gap: $spacing-lg;
}

.nav-btn {
	width: 36px;
	height: 36px;
	border-radius: 50%;
	background-color: $primary-light-blue;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&:active {
		transform: scale(0.95);
	}
}

.month-title {
	font-size: $font-size-title-1;
	font-weight: $font-weight-semibold;
	color: $text-dark-gray;
	min-width: 120px;
	text-align: center;
}

.today-btn {
	padding: $spacing-sm $spacing-lg;
	background-color: $primary-blue;
	color: $card-white;
	border: none;
	border-radius: $border-radius-md;
	font-size: $font-size-body;
	
	&:active {
		transform: scale(0.95);
	}
}

.week-header {
	display: flex;
	background-color: $card-white;
	border-bottom: 1px solid $border-gray;
}

.week-day {
	flex: 1;
	text-align: center;
	padding: $spacing-md 0;
	font-size: $font-size-body;
	font-weight: $font-weight-semibold;
	color: $text-light-gray;
}

.calendar-grid {
	display: flex;
	flex-wrap: wrap;
	background-color: $card-white;
}

.date-cell {
	width: calc(100% / 7);
	height: 80px;
	border-right: 1px solid $border-gray;
	border-bottom: 1px solid $border-gray;
	padding: $spacing-xs;
	display: flex;
	flex-direction: column;
	align-items: center;
	position: relative;
	cursor: pointer;
	
	&.other-month {
		background-color: $background-gray;
		
		.date-number {
			color: $text-light-gray;
		}
	}
	
	&.today {
		background-color: $primary-light-blue;
		
		.date-number {
			color: $primary-blue;
			font-weight: $font-weight-semibold;
		}
	}
	
	&.selected {
		background-color: $primary-blue;
		
		.date-number {
			color: $card-white;
			font-weight: $font-weight-semibold;
		}
		
		.schedule-dot {
			background-color: rgba(255, 255, 255, 0.8);
		}
		
		.more-count {
			color: $card-white;
		}
	}
	
	&.has-schedule {
		background-color: rgba(59, 130, 246, 0.05);
	}
	
	&:active {
		background-color: rgba(59, 130, 246, 0.1);
	}
}

.date-number {
	font-size: $font-size-body;
	color: $text-dark-gray;
	margin-bottom: $spacing-xs;
}

.schedule-dots {
	display: flex;
	flex-wrap: wrap;
	gap: 2px;
	align-items: center;
	justify-content: center;
}

.schedule-dot {
	width: 6px;
	height: 6px;
	border-radius: 50%;
	
	&.priority-urgent {
		background-color: $urgent-red;
	}
	
	&.priority-high {
		background-color: $high-orange;
	}
	
	&.priority-medium {
		background-color: $medium-purple;
	}
	
	&.priority-low {
		background-color: $low-gray;
	}
}

.more-count {
	font-size: 10px;
	color: $text-light-gray;
	margin-left: 2px;
}

.selected-date-schedules {
	padding: $spacing-lg;
}

.section-title {
	margin-bottom: $spacing-lg;
	
	text {
		font-size: $font-size-title-2;
		font-weight: $font-weight-semibold;
		color: $text-dark-gray;
	}
}

.schedule-list {
	// 日程卡片样式已在组件中定义
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60px $spacing-lg;
	text-align: center;
}

.empty-text {
	margin: $spacing-lg 0;
	font-size: $font-size-body;
	color: $text-light-gray;
}

.add-schedule-btn {
	padding: $spacing-md $spacing-xl;
	background-color: $primary-blue;
	color: $card-white;
	border: none;
	border-radius: $border-radius-md;
	font-size: $font-size-body;
	
	&:active {
		transform: scale(0.95);
	}
}
</style> 